<!-- 列表查找 -->
<template>
  <div class="tableSearch">
    <el-popover
      placement="bottom"
      width="500"
      trigger="click"
      popper-class="tableSearch-popover"
    >
      <!-- @show="handleShow" -->
      <div solt="content">
        <el-popover
          @show="handleShow"
          placement="bottom"
          trigger="click"
          ref="popover"
          popper-class="table-search-condition"
        >
          <div>
            <div class="condition-list" v-if="searchShow">
              <template v-for="(item, index) in searchList">
                <span
                  v-if="!item['isNoSearch']"
                  :key="index"
                  class="poptip-condition-item"
                  @click="handleFilter(item)"
                >
                  {{ item.label }}
                  <br />
                </span>
              </template>
            </div>
          </div>
          <el-tag slot="reference" class="cp"> 添加检索条件 </el-tag>
        </el-popover>
      </div>
      <!-- 表单提交 -->
      <el-form
        ref="formSearch"
        label-width="150px"
        @keyup.enter.native="handleSearch()"
        @submit.native.prevent
      >
        <!-- 搜索项渲染 -->
        <template v-for="(item, index) in addForm.list">
          <el-form-item :label="item.label" :key="item.key">
            <div class="form-item-content">
              <template v-if="item.type == 'time'">
                <el-date-picker
                  v-if="item.isDetailsTime"
                  value-format="yyyy-MM-dd"
                  v-model="item.value"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :unlink-panels="true"
                  :picker-options="pickerOptions"
                >
                </el-date-picker>
                <el-date-picker
                  v-else
                  v-model="item.value"
                  type="monthrange"
                  value-format="yyyy-MM-dd"
                  start-placeholder="开始月份"
                  end-placeholder="结束月份"
                  :unlink-panels="true"
                  :picker-options="pickerOptions"
                >
                </el-date-picker>
                <el-button
                  type="primary"
                  class="ml10"
                  :icon="
                    item.isDetailsTime ? 'el-icon-s-unfold' : 'el-icon-s-fold'
                  "
                  @click="item.isDetailsTime = !item.isDetailsTime"
                ></el-button>
              </template>
              <template v-else-if="item.type == 'number'">
                <el-input-number
                  v-model="item.value[0]"
                  :controls="false"
                ></el-input-number>
                <span>&nbsp;-&nbsp;</span>
                <el-input-number
                  v-model="item.value[1]"
                  :controls="false"
                ></el-input-number>
              </template>
              <!-- allow-create -->
              <el-select
                v-else-if="item.type == 'select'"
                v-model="item.value"
                :placeholder="item.text"
                filterable
              >
                <el-option
                  v-for="(items, optionsIndex) in item['options']"
                  :key="optionsIndex"
                  :label="items.name"
                  :value="items.code"
                >
                </el-option>
              </el-select>
              <el-input v-else v-model="item.value"></el-input>

              <el-button
                type="danger"
                class="ml10"
                @click.prevent="removeItem(item, index)"
                >删除</el-button
              >
            </div>
          </el-form-item>
        </template>
      </el-form>

      <!-- 查询重置 -->
      <template v-if="addForm.list.length">
        <div class="button_type">
          <el-button @click="handleSearch" type="primary">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </template>
      <div class="ml10 tableStats-btn tableStats-btn-active" slot="reference">
        列表查找
      </div>
    </el-popover>
  </div>
</template>

<script>
import { debounce } from "@u/index";
import { Message } from "element-ui";

export default {
  name: "tableSearch",
  data() {
    return {
      searchShow: false,
      addForm: {
        list: [],
      },
      checkList: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "本月",
            onClick(picker) {
              picker.$emit("pick", [
                new Date(new Date().setDate(1)),
                new Date(),
              ]);
            },
          },
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一年",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 12);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  props: {
    searchList: {
      type: Array,
      default: () => [],
    },
  },
  computed: {},
  watch: {
    // 检索条件为空，移除checkList验证数组
    "addForm.list": {
      handler(val, oldVal) {
        if (val.length == 0) {
          this.checkList = [];
        }
      },
      deep: true,
    },
  },
  methods: {
    handleShow() {
      this.searchShow = true;
      this.$emit("show");
    },
    // 添加检索条件
    handleFilter(item, value) {
      let check = false;
      if (this.checkList.includes(item.label)) {
        this.$refs.popover.showPopper = false;
        check = true;
      }
      if (check) {
        Message({
          message: "不能重复添加",
          type: "error",
        });
        return;
      }
      if (item["serchType"] == "select") {
        if (Array.isArray(item.searchOptions)) {
          if (item.searchOptions.length === 1) {
            value = item.searchOptions[0].value;
          }
          this.addForm.list.push({
            value: value || "",
            key: item.prop,
            label: item.label,
            type: "select",
            options: item.searchOptions,
            text: `请选择${item.label}`,
            prop: item.prop,
          });
        } else {
          this.addForm.list.push({
            value: value || "",
            key: item.prop,
            label: item.label,
            type: "select",
            options: item.searchOptions,
            text: "选择项错误",
            prop: item.prop,
          });
        }

        this.checkList.push(item.label);
      } else if (item["serchType"] == "number") {
        this.addForm.list.push({
          value: value || [null, null],
          key: item.prop,
          label: item.label,
          type: "number",
          prop: item.prop,
        });
      } else if (item["serchType"] == "time") {
        this.addForm.list.push({
          value: "",
          key: Date.now(),
          label: item.label,
          type: "time",
          prop: item.prop,
          isDetailsTime: true,
        });
        this.checkList.push(item.label);
      } else {
        this.addForm.list.push({
          value: value || "",
          key: item.prop,
          label: item.label,
          type: "input",
          prop: item.prop,
        });
        this.checkList.push(item.label);
      }
      this.$refs.popover.showPopper = false;
    },
    // 移除检索项
    removeItem(item, index) {
      this.addForm.list.splice(index, 1);
      if (this.checkList.includes(item.label)) {
        this.checkList.splice(this.checkList.indexOf(item.label), 1);
      }

      this.handleSearch();
    },
    // 查询
    handleSearch: debounce(function () {
      let obj = {};

      this.addForm.list.forEach((item) => {
        obj[item.prop] = item.value;
      });
      Object.keys(obj).forEach((item) => {
        obj[item] === "" ? delete obj[item] : "";
      });

      this.$emit("searchMethods", obj);
    }, 300),
    // 重置
    handleReset() {
      this.$set(this.addForm, "list", []);
      this.$emit("searchMethods", {});
      this.$refs.popover.showPopper = false;
    },
    // 重置搜索项
    reset() {
      this.$set(this.addForm, "list", []);
    },
    handleHide() {
      this.$refs.popover.showPopper = false;
    },
    // 读取缓存设置默认查询条件
    setCondition(params) {
      for (let key in params) {
        for (let i = 0; i < this.searchList.length; i++) {
          if (this.searchList[i].prop == key) {
            let value = params[key];
            if (this.searchList[i]["type"] == "select")
              value = this.isArray(value) ? value[0] : value;
            this.handleFilter(this.searchList[i], value);
            continue;
          }
        }
      }
    },
    isArray(o) {
      return Object.prototype.toString.call(o) == "[object Array]";
    },
  },
  created() {},
  mounted() {},
};
</script>
<style lang="less" scoped>
.tableSearch {
  display: inline-block;
  margin-left: 5px;
  .handle-btn {
    padding: 8px 24px;
    background: #027aff;
    border-radius: 4px;
    color: #ffffff;
    border: 1px solid #027aff;
    line-height: 1;
    font-size: 14px;
  }
}
</style>
